package com.credithc.eagleeye.api.utils;
import com.credithc.eagleeye.api.constants.ApiEnum;
import com.credithc.eagleeye.api.vo.AuthTokenVo;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2018年12月04日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
public class ServletUtils {
    public static AuthTokenVo getAuthTokenVo(final HttpServletRequest request) {
        AuthTokenVo authTokenVo=null;
        try {
            //获取token
            String token = getRequestToken(request);
            authTokenVo = JWTUtils.getInstance().decodeJWT(token);
        } catch (Exception ex) {
        }
        return authTokenVo;
    }

    /**
     * 获取请求中的token
     *
     * @param request
     * @return
     */
    public static String getRequestToken(final HttpServletRequest request) {
        //从header获取
        String token = request.getHeader(ApiEnum.API_HEADER_TOKEN);
        //从cookie获取
        if (StringUtils.isBlank(token)) {
            token = getRequestCookie(request, ApiEnum.API_COOKIE_TOKEN);
        }
        return token;
    }
    /**
     * 获取请求中的cookie
     *
     * @param request
     * @return
     */
    public static String getRequestCookie(final HttpServletRequest request, String cookieName) {
        //从cookie获取
        String cookieValue = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), cookieName)) {
                    cookieValue = cookie.getValue();
                    break;
                }
            }
        }
        return cookieValue;
    }
}
